const {serviceId, bindPassword, cubeSendUuidNotify,
  cubeReceiveUuidWrite,parseRes,writeBLECharacteristicValue,
  reply,bluetoothAdapterState,
  discovery,parseAdvertisData,closeCube,connect} = require('../../utils/bluetooth');
const {ab2hex, alert, array2arrayBuffer,
  digit2hex, getSeqNum, isIOS,
  log,jump,query2obj,pageDeltaInStack,cubeIsOnline,goToDeviceInfo,whenConnectedSaveInfo,setCubeInfo,
  obj2query,getCubeName,json2string} = require('../../utils/util');
const {Event} = require('../../utils/constant');

let serialNumber;

const app = getApp();

Page({
  data: {
    matchStatus:2//扫描中2，失败0，成功1
  },
  onLoad: function (option) {

    const that = this;

    this.fail = this.fail.bind(this);
    this.handleSerialNumber = this.handleSerialNumber.bind(this);

    // console.log(json2string(option))

    if(option&&option.q){
      try{
        //解析普通二维码
        const q = decodeURIComponent(option.q);
        const params = query2obj(q);
        serialNumber = params.id;
        // that.handleSerialNumber();
      }catch(e){
        log('string'===typeof e?e:JSON.stringify(e));
        that.fail();
      }
    }else if(option&&option.id){
      //从其它页面，比如devices页面，跳转来的
      serialNumber = option.id;
      // that.handleSerialNumber();
    }else if(option&&option.scene){
      //解析小程序码
      try{
        const q = decodeURIComponent(option.scene);
        const params = query2obj(q);
        serialNumber = params.id;
        // that.handleSerialNumber();
      }catch(e){
        log('string'===typeof e?e:JSON.stringify(e));
        that.fail();
      }
    }else{
      that.fail();
    }
    // app.event.on(Event.BluetoothAdapterStateChange, that.BluetoothAdapterStateChangeHandler, that);
  },
  onUnload:function () {
    // app.event.off(Event.BluetoothAdapterStateChange, this.BluetoothAdapterStateChangeHandler);
    wx.stopBluetoothDevicesDiscovery();
  },
  onShow:function(){
    // console.log(serialNumber)
    if(serialNumber){
      this.handleSerialNumber();
    }
  },
  handleSerialNumber:function(){

    this.searchDevices();
    // return;
    //
    // const that = this;
    //
    // bluetoothAdapterState({
    //   success:function(){
    //     that.searchDevices();//微信内或者小程序内扫码时，小程序会进入后台，目前的业务场景是，小程序进入后台时，连接要断开（在app的onhide中断开）
    //     return;
    //
    //     const lastCubeSerialNumber = wx.getStorageSync('lastCubeSerialNumber');
    //     const online = cubeIsOnline();
    //     if(serialNumber+'' === lastCubeSerialNumber+''){
    //       if(online){
    //         that.setData({matchStatus:1});
    //         setTimeout(function () {
    //           //const lastCubeName = wx.getStorageSync('lastCubeName');
    //           goToDeviceInfo({serialNumber,needConnect:0});
    //         },2500);
    //       }else{
    //         that.searchDevices();
    //       }
    //     }else{
    //       if(online){
    //         closeCube(function () {
    //           that.searchDevices();
    //         });
    //       }else{
    //         that.searchDevices();
    //       }
    //     }
    //   },
    //   fail:function () {
    //     // that.setData({matchStatus:0});
    //     // wx.showToast({title: '请打开蓝牙', icon: 'none'});
    //     jump({pageName:'bluetoothClosed',type:1});
    //   }
    // });
  },
  BluetoothAdapterStateChangeHandler:function(available){
    if (available) {
      this.searchDevices();
    } else {
      this.setData({matchStatus: 0});
    }
  },
  onHide:function () {
    //页面回退
    wx.stopBluetoothDevicesDiscovery();
  },
  fail:function(isJump=true){
    wx.stopBluetoothDevicesDiscovery();
    this.setData({matchStatus:0});
    isJump&&setTimeout(function () {
      jump({pageName:'devices'});
    },200);
  },

  searchDevices:function () {
    const that = this;
    that.setData({matchStatus:2});

    let isFound = false;

    bluetoothAdapterState({
      success:function () {
        discovery(function (devices) {
          try{
            const dv = devices.devices[0];
            const {localName,name,deviceId,advertisData} = dv; //deviceId是mac地址，cube重启后可能会变
            const {serialNumber:serialNumberFound,productId} = parseAdvertisData(advertisData);
            if(serialNumberFound+'' === serialNumber+'' && !isFound){
              isFound = true;
              // const cubeName = getCubeName({serialNumber});
              wx.stopBluetoothDevicesDiscovery({
                complete: function () {
                  //stopBluetoothDevicesDiscovery成功后，再调用connect，非常重要。
                  log(`found device: deviceId=${deviceId}, serialNumberFound=${serialNumber}`);
                  log(`willConnect device: deviceId=${deviceId}, serialNumber=${serialNumber}`);
                  connect({
                      deviceId,
                      connectSuccess: function () {
                        log(`serialNumber:${serialNumber},deviceId:${deviceId} connectSuccess`);
                        whenConnectedSaveInfo({serialNumber,cubeName:getCubeName({serialNumber})});
                        // setCubeInfo({serialNumber, info: {deviceId, cubeName, matchStatus: 3}});
                        setCubeInfo({serialNumber, info: {deviceId, cubeName:getCubeName({serialNumber})}});
                        that.setData({matchStatus:1});
                        setTimeout(function () {
                          goToDeviceInfo({serialNumber,needConnect:0})
                        },1500);
                      },
                      fail: function () {
                        that.setData({matchStatus:0});
                      },
                      complete: function () {
                        wx.setStorageSync('autoReconnect', 1);
                      }
                    },
                  );
                }
              });
            }
          }catch(e){
          }
        })
      },
      fail:function () {
        that.fail(false);
      }
    })
  },
  onPullDownRefresh: function(){
    this.searchDevices();
  },
  rematch:function () {
    this.searchDevices();
  }

});
